import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { getInfoStatus } from '../api/info'

export const useEnterpriseStore = defineStore('enterprise', () => {
  // 企业备案状态，3表示已通过备案
  const profileStatus = ref(null)
  const isStatusLoading = ref(false)
  const isStatusChecked = ref(false)

  // 统一将接口返回值转换为可比较的数字状态
  const normalizeStatus = (value) => {
    const rawStatus = value?.data ?? value
    const numericStatus = typeof rawStatus === 'number' ? rawStatus : Number(rawStatus)
    return Number.isNaN(numericStatus) ? null : numericStatus
  }

  // 是否已通过备案
  const isProfileApproved = computed(() => profileStatus.value === 3)

  // 获取企业备案状态
  async function fetchProfileStatus() {
    try {
      isStatusLoading.value = true
      const statusResponse = await getInfoStatus()
      const normalizedStatus = normalizeStatus(statusResponse)
      profileStatus.value = normalizedStatus
      return normalizedStatus
    } catch (error) {
      console.error('获取企业备案状态失败:', error)
      return null
    } finally {
      isStatusLoading.value = false
      isStatusChecked.value = true
    }
  }

  // 更新企业备案状态
  function updateProfileStatus(status) {
    profileStatus.value = normalizeStatus(status)
  }

  // 重置企业备案状态
  function resetProfileStatus() {
    profileStatus.value = null
    isStatusChecked.value = false
  }

  return {
    profileStatus,
    isStatusLoading,
    isStatusChecked,
    isProfileApproved,
    fetchProfileStatus,
    updateProfileStatus,
    resetProfileStatus
  }
})
